import type { Form } from "@/interface/formData";
import axios from "axios";
import { ElMessage } from "element-plus";
import { computed, ref } from "vue";
import { useUserStore } from "@/stores/userStore";
import type { Announcement } from "@/interface/announcementData";


export default function () {


      const { useridentityfer } = useUserStore();
      const works = ref<Form[]>([]); //请求后数据集
      const announcements = ref<Announcement[]>([]);




      const isPunchedIn = ref(false);   // 是否上班打卡
      const isFinished = ref(false);    // 是否下班打卡完成


      // 今日工作信息（这里只做示例，可以后端接口替换）
      const todayJob = ref<Form | null>();



      //请求后端

      async function jobIsInWork() {
            await axios.get(`/api/student/jobIsInWork/${useridentityfer}`)
                  .then(response => {
                        // console.log("response:", response);
                  })
                  .catch(error => {
                        ElMessage.warning("jobIsInWork请求失败");
                        // console.log("jobIsInWork请求失败--", error);
                  })
      }

      async function getStudentWorks() {
            await axios.get(`/api/student/myWorks/${useridentityfer}`)
                  .then(response => {
                        works.value = response.data.data;
                        // console.log("responseValue::", response.data.data);
                        // console.log("worksValue::", works.value);
                  })
                  .catch(error => {
                        ElMessage.warning("请求失败");
                  })

      }

      async function getannouncements() {
            const date = new Date();
            const month = date.getMonth() + 1;
            await axios.get(`/api/student/announcements/${month}`)
                  .then(response => {
                        announcements.value = response.data.data;
                  })
                  .catch(error => {
                        ElMessage.warning("请求失败");
                  })

      }


      async function REQ_getTodayJob() {
            const date = new Date();
            await axios.get(`/api/student/todayJob/${useridentityfer}`)
                  .then(response => {
                        todayJob.value = response.data.data;
                        console.log("今日工作L:", todayJob.value)
                  })
                  .catch(error => {
                        ElMessage.warning("请求失败");
                  })

      }

      async function REQ_jobPunch(isPunchedIn: Boolean) {
            await axios.get(`/api/student/jobPunch/${isPunchedIn}/${todayJob.value?.id}/${useridentityfer}`)
                  .then(response => {
                        ElMessage("打卡成功")
                  })
                  .catch(error => {
                        ElMessage.warning("请求失败");
                  })

      }





      // 今日工作
      function togglePunch() {
            if (!isPunchedIn.value) {
                  // 上班打卡逻辑
                  isPunchedIn.value = true;
                  REQ_jobPunch(isPunchedIn.value);
            } else {
                  // 下班打卡逻辑
                  isPunchedIn.value = false;
                  isFinished.value = true;
                  REQ_jobPunch(isPunchedIn.value);
            }
      }







      //状态卡片

      let reviewed = ref(0);
      let inHand = ref(0)
      let completed = ref(0)

      function statusCardInit() {
            works.value.filter((item) => {
                  if (item.process === "2") {
                        reviewed.value++;
                  }
                  if (item.process === "3") {
                        inHand.value++;
                  }
                  if (item.process === "4") {
                        completed.value++;
                  }
            })
      }

      const statusCard = computed(() => {
            return {
                  reviewed: reviewed.value != 0 ? reviewed.value : 0, //已接取
                  inHand: inHand.value != 0 ? inHand.value : 0, // 进行中
                  completed: completed.value != 0 ? completed.value : 0, //已处理 已完成
            };
      });




      //公告




      //图表
      const source = ref<
            { product: string; 零工: number; 短期兼职: number; 长期兼职: number }[]
      >([]);

      const ChartData = ref({
            dimensions: ["product", "零工", "短期兼职", "长期兼职"],
            source: source,
      });


      const workProcessCount = ref<Record<string, Record<string, number>>>({});

      function countWorks(data: Form[]) {
            // 初始化统计对象
            const statusMap: Record<string, Record<string, number>> = {};

            data.forEach((work) => {
                  const { process, jobType } = work;

                  // 统计 status
                  if (!statusMap[process]) {
                        statusMap[process] = { "1": 0, "2": 0, "3": 0 };
                  }
                  statusMap[process][jobType] = (statusMap[process][jobType] || 0) + 1;
            });
            workProcessCount.value = statusMap;
            updateSource();
      }

      function updateSource() {
            source.value = [
                  {
                        product: "所有兼职",
                        零工:
                              (workProcessCount.value["1"]?.["1"] || 0) +
                              (workProcessCount.value["2"]?.["1"] || 0) +
                              (workProcessCount.value["3"]?.["1"] || 0) +
                              (workProcessCount.value["4"]?.["1"] || 0) +
                              (workProcessCount.value["5"]?.["1"] || 0),
                        短期兼职:
                              (workProcessCount.value["1"]?.["2"] || 0) +
                              (workProcessCount.value["2"]?.["2"] || 0) +
                              (workProcessCount.value["3"]?.["2"] || 0) +
                              (workProcessCount.value["4"]?.["2"] || 0) +
                              (workProcessCount.value["5"]?.["2"] || 0),
                        长期兼职:
                              (workProcessCount.value["1"]?.["3"] || 0) +
                              (workProcessCount.value["2"]?.["3"] || 0) +
                              (workProcessCount.value["3"]?.["3"] || 0) +
                              (workProcessCount.value["4"]?.["3"] || 0) +
                              (workProcessCount.value["5"]?.["3"] || 0),
                  },
                  {
                        product: "待完成",
                        零工: workProcessCount.value["2"]?.["1"] || 0,
                        短期兼职: workProcessCount.value["2"]?.["2"] || 0,
                        长期兼职: workProcessCount.value["2"]?.["3"] || 0,
                  },
                  {
                        product: "已完成",
                        零工: workProcessCount.value["4"]?.["1"] || 0,
                        短期兼职: workProcessCount.value["4"]?.["2"] || 0,
                        长期兼职: workProcessCount.value["4"]?.["3"] || 0,
                  },
                  {
                        product: "已结算",
                        零工: workProcessCount.value["5"]?.["1"] || 0,
                        短期兼职: workProcessCount.value["5"]?.["2"] || 0,
                        长期兼职: workProcessCount.value["5"]?.["3"] || 0,
                  }
            ];
      }



      return {
            getStudentWorks,
            statusCardInit,
            getannouncements,
            countWorks,
            jobIsInWork,

            REQ_getTodayJob,
            togglePunch,
            isPunchedIn,
            todayJob,
            isFinished,
            statusCard,
            ChartData,
            source,
            works,
            announcements
      }
}